import axios from 'axios'

import sysConfig from '@/config'
import tool from '@/utils/tool'
import router from '@/router'

import { SiteStore } from '@/stores/site'

axios.defaults.baseURL = ''
axios.defaults.timeout = sysConfig.timeout

// HTTP request 拦截器
axios.interceptors.request.use(
  (config) => {
    let token = tool.cookie.get('TOKEN')
    if (token) {
      config.headers[sysConfig.token_name] = sysConfig.token_prefix + token
    }
   let site=  SiteStore();
 config.headers["aid"] =  site.aid;
  config.headers["mident"] =site.mident;

  




    if (!sysConfig.request_cache && config.method == 'get') {
      config.params = config.params || {}
      config.params['_'] = new Date().getTime()
    }
    Object.assign(config.headers, sysConfig.headers)
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

//FIX 多个API同时401时疯狂弹窗BUG
let MessageBox_401_show = false

// HTTP response 拦截器
axios.interceptors.response.use(
  (response) => {
    var { code, message, msg } = response.data



    if (code) {
      if (code == '2002') {

        ElMessageBox.confirm(
          msg ? msg : '连接数据库失败',
          '错误',
          {
            type: 'error',
            closeOnClickModal: false,
            center: true,
            showCancelButton: false,
            confirmButtonText: '关闭',
            beforeClose: (action, instance, done) => {

              done()
            }
          })

        return
      }
      if (code == '500') {

        ElMessageBox.confirm(
          JSON.stringify(response.data),
          '错误500',
          {
            type: 'error',
            closeOnClickModal: false,

            customStyle: 'width:80vw;max-width:80vw',
            showCancelButton: false,
            confirmButtonText: '关闭',
            beforeClose: (action, instance, done) => {

              done()
            }
          })

        return
      }
    }



    if (code && code == '401') {
      ElMessageBox.confirm(
        message ? message : '当前用户已被登出或无权限访问当前资源，请尝试重新登录后再操作。',
        '无权限访问2',
        {
          type: 'error',
          closeOnClickModal: false,
          center: true,
          confirmButtonText: '重新登录',
          beforeClose: (action, instance, done) => {
            MessageBox_401_show = false
            done()
          }
        }
      )
        .then(() => {
          router.replace({ path: '/login' })
        })
        .catch(() => { })
    } else {
      return response
    }
  },
  (error) => {
    if (error.response) {
      if (error.response.status == 404) {

        console.log(" 404，正在请求不存在的服务器记录！")

      } else if (error.response.status == 500) {


        console.log("Status:500，服务器发生错误！")


      } else if (error.response.status == 401) {
        console.log("401")
      } else {
        console.log("其它")
      }
    } else {
      console.log("服务器没有响应！")
    }

    return Promise.reject(error.response)
  }
)

function simplifyresponse(response) {


  var { code, status, message } = response.data

  if (!code) {
    return response.data
  }
  if (code != 20000) {

  } else {
    if (status == -2) {

    } else {
      return response.data.data
    }
  }
  return { status: -2 }
}
function syspara(data) {

  return data
}

var http = {
  /** get 请求
   * @param  {string} url 接口地址
   * @param  {object} params 请求参数
   * @param  {object} config 参数
   */
  get: function (url, params = {}, config = {}, onlydata = true) {
    params = syspara(params)
    return new Promise((resolve, reject) => {
      axios({
        method: 'get',
        url: url,
        params: params,
        ...config
      })
        .then((response) => {
          if (onlydata) {
            var res = simplifyresponse(response)

            resolve(res)
          } else {
            resolve(response.data)
          }
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  /** post 请求
   * @param  {string} url 接口地址
   * @param  {object} data 请求参数
   * @param  {object} config 参数
   */
  post: function (url, data = {}, config = {}, onlydata = true) {
    data = syspara(data)
    return new Promise((resolve, reject) => {
      axios({
        method: 'post',
        url: url,
        data: data,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        },
        ...config
      })
        .then((response) => {
          if (onlydata) {
            var res = simplifyresponse(response)

            resolve(res)
          } else {
            resolve(response.data)
          }
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  /** put 请求
   * @param  {string} url 接口地址
   * @param  {object} data 请求参数
   * @param  {object} config 参数
   */
  put: function (url, data = {}, config = {}) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'put',
        url: url,
        data: data,
        ...config
      })
        .then((response) => {
          resolve(response.data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  /** patch 请求
   * @param  {string} url 接口地址
   * @param  {object} data 请求参数
   * @param  {object} config 参数
   */
  patch: function (url, data = {}, config = {}) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'patch',
        url: url,
        data: data,
        ...config
      })
        .then((response) => {
          resolve(response.data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  /** delete 请求
   * @param  {string} url 接口地址
   * @param  {object} data 请求参数
   * @param  {object} config 参数
   */
  delete: function (url, data = {}, config = {}) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'delete',
        url: url,
        data: data,
        ...config
      })
        .then((response) => {
          resolve(response.data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  /** jsonp 请求
   * @param  {string} url 接口地址
   * @param  {string} name JSONP回调函数名称
   */
  jsonp: function (url, name = 'jsonp') {
    return new Promise((resolve) => {
      var script = document.createElement('script')
      var _id = `jsonp${Math.ceil(Math.random() * 1000000)}`
      script.id = _id
      script.type = 'text/javascript'
      script.src = url
      window[name] = (response) => {
        resolve(response)
        document.getElementsByTagName('head')[0].removeChild(script)
        try {
          delete window[name]
        } catch (e) {
          window[name] = undefined
        }
      }
      document.getElementsByTagName('head')[0].appendChild(script)
    })
  }
}

export default http
